<template>
  <div class="model-container">
    <div class="listName">商家管理</div>
    <!--搜索-->
    <el-card v-if="getUser().sellerId === null" shadow="never">
      <div slot="header" class="clearfix">
      <span>快捷搜索</span>
      <div class="btns-wrapper-right">
        <el-button v-if="!searchShow" icon="el-icon-arrow-down" @click="searchShow = true"/>
        <el-button v-else icon="el-icon-arrow-up" @click="searchShow = false"/>
      </div>
    </div>
      <el-collapse-transition>
        <div v-show="searchShow" class="cardbody">
          <el-form ref="seacherParam" :model="seacherParam">
            <el-row :gutter="10">
              <el-col :xl="5" :lg="6" :md="6" :sm="8" >
                <el-col :xl="7" :lg="7" :md="8" :sm="8" class="input-name">店铺名称</el-col>
                <el-col :xl="17" :lg="17" :md="16" :sm="16">
                  <el-form-item prop="sellerName">
                    <el-input v-model="seacherParam.sellerName" size="small" placeholder="请输入店铺名称"/>
                  </el-form-item>
                </el-col>
              </el-col>
              <el-col :xl="5" :lg="6" :md="6" :sm="8" >
                <el-col :xl="7" :lg="7" :md="8" :sm="8" class="input-name">商家</el-col>
                <el-col :xl="17" :lg="17" :md="16" :sm="16">
                  <el-form-item prop="sellerId">
                    <el-select v-model="seacherParam.sellerId" size="small" placeholder="请选择">
                      <el-option v-for="(item,index) in sellerList" :key="index" :label="item.sellerName" :value="item.sellerId" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-col>
            </el-row>
            <div class="cardfooter">
              <el-button type="primary" size="mini" plain @click="seachFun">查询</el-button>
              <el-button type="warning" size="mini" plain @click="resetFun">重置</el-button>
            </div>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>
    <!--表格-->
    <el-card style="margin-top: 10px">
      <div slot="header" class="clearfix">
        <div class="btns-wrapper-left">
          <el-button v-if="getUser().sellerId === null" type="primary" plain @click="add">新增</el-button>
          <el-button v-if="getUser().sellerId === null" type="danger" plain @click="del(0)">批量删除</el-button>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table v-loading="!dataOption" :data="dataOption" stripe border empty-text="暂无数据" @selection-change="changeFun">

          <el-table-column align="center" type="selection" width="55"/>

          <el-table-column align="center" prop="userName" label="用户名"/>

          <el-table-column align="center" prop="sellerName" label="店铺名称"/>

          <el-table-column align="center" prop="addrStreet" label="所在地区"/>

          <el-table-column align="center" prop="contactPerson" label="负责人姓名"/>

          <el-table-column align="center" prop="contactMobile" label="联系电话"/>

          <el-table-column align="center" prop="fansNumber" label="粉丝数"/>

          <el-table-column align="center" prop="createTime" label="创建时间"/>

          <el-table-column v-if="getUser().sellerId === null" align="center" label="同步商品">
            <template slot-scope="scope"><span style="color: #1e6abc;cursor: pointer" @click="synchronous(scope.row)">同步商品</span></template>
          </el-table-column>

          <el-table-column v-if="getUser().sellerId === null" align="center" label="状态">
            <template slot-scope="scope"><span :class="scope.row.runningStatus === 1 ? 'statusClass' : 'statusClassnew'" class="statusClass" @click="runningStatusFun(scope.row)">{{ runningStatusVal(scope.row.runningStatus) }}</span></template>
          </el-table-column>

          <el-table-column v-if="getUser().sellerId === null" align="center" label="热推">
            <template slot-scope="scope"><span :class="scope.row.isHotPush === 1 ? 'statusClass' : 'statusClassnew'" style="cursor: pointer" @click="isHotPushFun(scope.row)">{{ isHotPushVal(scope.row.isHotPush) }}</span></template>
          </el-table-column>

          <el-table-column align="center" label="是否开启全网购">
            <template slot-scope="scope"><el-switch v-model="scope.row.isNetwork" active-color="#13ce66" inactive-color="#ff4949" @change="switchChange(scope.row)"/></template>
          </el-table-column>

          <el-table-column align="center" label="操作" width="200px">
            <template slot-scope="scope">

              <el-button title="查看" type="primary" circle class="table-icon" @click="detailsFun(scope.row)"><i class="iconfont icon-chakan2"/></el-button>

              <el-button v-if="scope.row.censorStatus !== 3" title="编辑" type="primary" circle icon="el-icon-edit" class="table-icon" @click="edit(scope.row)"/>

              <el-button v-if="getUser().sellerId === null" title="删除" type="warning" circle icon="el-icon-delete" class="table-icon" @click="del(scope.row)"/>

            </template>
          </el-table-column>

        </el-table>

        <!--分页-->
        <el-pagination
          :current-page="pageNo"
          :page-sizes="[10, 20, 30]"
          :page-size="pageSize"
          :total="rowCount"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </el-card>

    <!--弹框-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogState"
      :close-on-click-modal="false"
      :before-close="handleClose"
      top="5vh"
      width="70%">
      <template>
        <div style="padding: 30px 60px;">
          <el-transfer
            v-if="transferStatus"
            v-model="synchronousList"
            :titles="['选择全部商品', '选择已选商品']"
            :button-texts="['到左边', '到右边']"
            :props="{
              key: 'itemId',
              label: 'itemTitle'
            }"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}'
            }"
            :data="generateData"
            :filter-method="filterMethod"
            filterable
            @change="handleChange">
            <span slot-scope="{ option }">{{ option.itemTitle }} - {{ option.itemId }}</span>
            <span slot="left-footer">商品名称 - 商品ID </span>
            <span slot="right-footer">商品名称 - 商品ID </span>
          </el-transfer>
          <div style="display: flex;justify-content: center;margin-top: 20px">
            <el-button slot="left-footer" type="primary" size="small" @click="submitSynchronous">提交</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import * as commodity from '../../api/commodity'
import * as merchant from '../../api/merchant'
import { getUserInformation } from '@/utils/auth'
export default {
  data() {
    return {
      // 同步到商家
      generateData: [],
      synchronousList: [],
      transferStatus: true,
      synchronousData: '',
      delMovedKeysData: '',
      merchantsListAll: '',

      // 页面搜索
      seacherParam: {
        sellerName: '',
        sellerId: ''
      },
      sellerList: null,
      searchShow: false,
      pageNo: 1,
      pageSize: 10,
      rowCount: null, // 总条数
      // 弹框
      dialogType: 1, // 1--增加  2--编辑  3--审核   4--重新审核
      dialogState: false,
      // 按钮状态
      buttonState: false,
      // 列表数据
      dataOption: null,
      // 提交内容
      datavalID: []
    }
  },
  computed: {
    dialogTitle() {
      if (this.dialogType === 1) {
        return '新增商家'
      }
      if (this.dialogType === 2) {
        return '编辑商家'
      } else {
        return '查看'
      }
    }

  },
  beforeMount() {
    const searchType = this.$route.params.search // 类型
    if (searchType) {
      this.seacherParam = JSON.parse(sessionStorage.getItem('searchData'))
      //this.pageNo = JSON.parse(sessionStorage.getItem('pageContextData'))
      this.searchShow = true
      this.seachFun()
    } else {
      sessionStorage.removeItem('searchData')
     // sessionStorage.removeItem('pageContextData')
      this.getList()
    }
    this.sellerListFun()
  },
  methods: {
    // 获取用户信息
    getUser() {
      return JSON.parse(getUserInformation())
    },
    // 穿梭框
    synchronous(data) {
      this.dialogState = true
      this.transferStatus = true
      this.synchronousData = data
      this.getMerchantsListAll()
      this.getSynchronous(data)
    },
    // 获取所有商品
    getMerchantsListAll() {
      merchant.getMerchantsListAll().then(res => {
        if (res.data.code === 1) {
          this.generateData = res.data.data
        }
      })
    },
    // 获取以同步
    getSynchronous(data) {
      const param = {
        sellerId: data.sellerId
      }
      merchant.getSynchronous(param).then(res => {
        if (res.data.code === 1) {
          this.merchantsListAll = res.data.data
          const dataList = res.data.data
          for (const val of dataList) {
            this.synchronousList.push(val.itemId)
          }
        }
      })
    },
    // 提交同步
    submitSynchronous() {
      if (this.synchronousList.length > 0) {
        const param = {
          sellerId: this.synchronousData.sellerId,
          itemIds: this.synchronousList
        }
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        merchant.saveBatchList(param).then(res => {
          loading.close()
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '同步成功'
            })
          }
        })
        this.delSynchronous(0)
      } else {
        this.delSynchronous(1)
      }
    },
    // 删除同步
    delSynchronous(data) {
      if (this.delMovedKeysData === '') {
        return false
      }
      const param = []
      for (const val of this.merchantsListAll) {
        for (const data of this.delMovedKeysData) {
          if (data === val.itemId) {
            param.push(val.id)
          }
        }
      }
      merchant.delBatchList(param).then(res => {
        if (res.data.code === 1) {
          if (data === 0) {
            console.log('移除商家')
          } else {
            this.$message({
              type: 'success',
              message: '同步成功'
            })
          }
        }
      })
    },
    filterMethod(query, item) {
      if (item.itemTitle.indexOf(query) > -1 || item.itemId.indexOf(query) > -1) {
        return true
      }
    },
    handleChange(value, direction, movedKeys) {
      if (direction === 'left') {
        this.delMovedKeysData = movedKeys
      }
    },
    seachFun() {
      if (!this.searchStatus) {
        this.pageNo = 1
      }
      const param = {
        current: this.pageNo,
        size: this.pageSize
      }
      const arr = []
      for (const key in this.seacherParam) {
        if (this.seacherParam[key] !== '') {
          arr.push('&' + key + '=' + this.seacherParam[key])
        }
      }
      const url = arr.join('')
      merchant.searchMerchantsList(param, url).then(res => {
        if (res.data.code !== 1) {
          this.$message.error(res.data.msg)
          return false
        }
        if (res.data.data === 'null' || res.data.data === null) {
          return false
        }
        // 初始话表格数据
        this.dataOption = res.data.data.records
        // 初始化分页数据
        this.rowCount = res.data.data.total
        this.pageSize = res.data.data.size
        this.searchStatus = false
      })
    },
    getList(cb) {
      const param = {
        current: this.pageNo,
        size: this.pageSize,
        censorStatus: 4
      }
      if (this.getUser().sellerId !== null) {
        param.sellerId = this.getUser().sellerId
      }
      merchant.getMerchantsList(param).then(res => {
        if (res.data.code !== 1) {
          this.$message.error(res.data.msg)
          return false
        }
        if (res.data.data === 'null' || res.data.data === null) {
          return false
        }
        const records = res.data.data.records
        for (const val of records) {
          if (val.isNetwork === 0) {
            val.isNetwork = false
          } else {
            val.isNetwork = true
          }
        }
        // 初始话表格数据
        this.dataOption = records
        // 初始化分页数据
        this.rowCount = res.data.data.total
        this.pageSize = res.data.data.size
      })
    },
    sellerListFun() {
      const param = {
        current: 1,
        size: 9999
      }
      commodity.getMerchantsListAll(param).then(res => {
        if (res.data.code === 1) {
          this.sellerList = res.data.data.records // 搜索用到
        }
      })
    },
    // 添加Banner
    addBanner(data) {
      this.$router.push({
        name: '/v1/bannerstore',
        params: {
          sellerId: data.sellerId
        }
      })
    },
    // 新增
    add() {
      this.$router.push({
        name: '/v1/merchant_add',
        params: {
          dialogType: 1
        }
      })
    },
    // 编辑
    edit(data) {
      this.$router.push({
        name: '/v1/merchant_add',
        params: {
          data: data,
          dialogType: 2
        }
      })
      sessionStorage.setItem('searchData', JSON.stringify(this.seacherParam))
    },
    // 查看
    detailsFun(data) {
      this.$router.push({
        name: '/v1/merchant_add',
        params: {
          data: data,
          dialogType: 3
        }
      })
      sessionStorage.setItem('searchData', JSON.stringify(this.seacherParam))
    },
    // 删除
    changeFun(data) {
      this.datavalID = data
    },
    del(data) {
      if (data === 0) {
        if (this.datavalID.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择商家!'
          })
        }
        return false
      }
      this.$confirm('确认要删除此商家吗,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delDataTable(data)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    delDataTable(data) {
      const shopID = []
      if (data === 0) {
        for (const val of this.datavalID) {
          shopID.push(val.catId)
        }
      } else {
        shopID.push(data.sellerId)
      }
      merchant.delMerchantsList(shopID).then(res => {
        if (res.data.code === 1) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        }
      })
    },
    // 是否全网购买
    switchChange(e) {
      const isNetwork = e.isNetwork === false ? 0 : 1
      const param = {
        sellerId: e.sellerId,
        isNetwork: isNetwork
      }
      merchant.editorUpdateIsNetwork(param).then(res => {
        if (res.data.code === 1) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getList()
        }
      })
    },
    // 启用/禁用
    runningStatusFun(data) {
      let runningStatus
      if (data.runningStatus === 1) {
        runningStatus = 0
      } else {
        runningStatus = 1
      }
      const param = {
        sellerId: data.sellerId,
        runningStatus: runningStatus
      }
      this.$confirm('是否启用或禁用此商家?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        merchant.statusMerchantsList(param).then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 热推
    isHotPushFun(data) {
      let isHotPush
      if (data.isHotPush === 1) {
        isHotPush = 0
      } else {
        isHotPush = 1
      }
      const param = {
        sellerId: data.sellerId,
        isHotPush: isHotPush
      }
      this.$confirm('是否设为热推?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        merchant.statusMerchantsList(param).then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },

    // 重置
    resetFun() {
      this.$refs.seacherParam.resetFields()
      this.pageNo = 1
      this.pageSize = 10
      sessionStorage.removeItem('pageContextData')
      sessionStorage.removeItem('searchData')
      for (const key in this.seacherParam) {
        this.seacherParam[key] = ''
      }
      this.getList()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageNo = val
      sessionStorage.setItem('pageContextData', JSON.stringify(val))
      if (this.seacherParam.sellerName !== '' ) {
        this.searchStatus = true
        this.seachFun()
      } else {
        this.getList()
      }
    },
    handleClose() {
      this.generateData = []
      this.synchronousList = []
      this.delMovedKeysData = ''
      this.transferStatus = false
      this.dialogState = false
    },
    sellerTypeVal(type) {
      if (type === '1') {
        return '店铺类型'
      } else {
        return '其他'
      }
    },
    runningStatusVal(type) {
      if (type === 1) {
        return '启用'
      } else {
        return '禁用'
      }
    },
    isHotPushVal(type) {
      if (type === 1) {
        return '热推'
      } else {
        return '设为热推'
      }
    },
    censorStatusVal(type) {
      if (type === 0) {
        return '待审核'
      } else if (type === 1) {
        return '已审核'
      } else if (type === 2) {
        return '重新审核'
      } else if (type === 3) {
        return '审核不通过'
      }
    }
  }
}
</script>
<style type="text/scss" lang="scss">
  .formBody {
    .el-dialog__body{
      padding: 10px;
    }
  }
  .el-transfer-panel{
    width: 500px;
    padding-bottom: 40px;
    .el-checkbox__label {
      .small {
        font-size: 10px;
        float: right;
        color: rgb(172, 165, 165);
      }
    }
  }
  .el-transfer-panel__body{
    height: 400px;
  }
  .el-transfer-panel__list.is-filterable{
    height: 355px;
  }
  .el-transfer-panel .el-transfer-panel__footer {
    padding: 6px 37px;
  }
</style>
<style type="text/scss" lang="scss" scoped>
  .formBody{
    height: 600px;
    overflow: auto;
  }
  .statusClass{
    cursor: pointer;
    color: #33CC00;
  }
  .statusClassnew{
    cursor: pointer;
    color: #FF0033;
  }
</style>
